package logic

import (
	"context"
	"encoding/json"
	"shopping/models/mysql"
	"shopping/models/redis"
	"strconv"
	"time"

	"shopping/shoppingrpc/internal/svc"
	"shopping/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductsListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductsListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductsListLogic {
	return &ProductsListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductsListLogic) ProductsList(in *shoppingrpc.ProductsListRequest) (*shoppingrpc.ProductsListResponse, error) {
	// todo: add your logic here and delete this line

	var product []mysql.Product
	offset := (in.Page - 1) * in.Size
	key := "productList" + strconv.Itoa(int(offset))
	var slice []*shoppingrpc.ProductList
	get := redis.Rdb.Get(key)
	if get.Val() == "" {
		query := mysql.Db.Debug().Offset(int(offset)).Limit(int(in.Size))
		if in.Name != "" {
			query = query.Where("name like ?", "%"+in.Name+"%")
		}
		query.Debug().Order("price desc").Order("created_at desc").Find(&product)

		for _, v := range product {
			list := shoppingrpc.ProductList{
				Id:    int64(v.ID),
				Name:  v.Name,
				Price: float32(v.Price),
			}
			slice = append(slice, &list)
		}
		marshal, err := json.Marshal(slice)
		if err != nil {
			return nil, err
		}
		redis.Rdb.Set(key, marshal, time.Minute*24)
	} else {
		err := json.Unmarshal([]byte(get.Val()), &slice)
		if err != nil {
			return nil, err
		}
	}
	return &shoppingrpc.ProductsListResponse{List: slice}, nil
}
